<template>
	<view class="report-detail">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<!-- 服务信息 -->
		<view class="service-info">
			<view class="service-image">
				<image :src="orderInfo.image" mode="aspectFill"></image>
			</view>
			<view class="service-content">
				<view class="service-title">{{ orderInfo.title }}</view>
				<view class="service-meta">
					<text class="location">{{ orderInfo.store }} {{ orderInfo.technician }}</text>
					<text class="time">{{ orderInfo.time }}</text>
				</view>
				<view class="price-info">
					<text class="original-price">¥{{ orderInfo.price }}</text>
					<text class="member-price">会员价{{ orderInfo.memberPrice }}</text>
				</view>
			</view>
		</view>
		
		<!-- 举报选项 -->
		<view class="report-options">
			<view class="option-title">请选择反馈类型</view>
			<view class="options-grid">
				<view 
					v-for="(option, index) in reportOptions" 
					:key="index"
					class="option-item"
					:class="{ active: selectedOptions.includes(option) }"
					@tap="toggleOption(option)"
				>
					{{ option }}
				</view>
			</view>
		</view>
		
		<!-- 补充说明 -->
		<view class="report-detail-input">
			<textarea 
				v-model="reportContent"
				placeholder="请输入申请原因"
				class="detail-textarea"
				maxlength="500"
			></textarea>
		</view>
		
		<!-- 图片/视频上传 -->
		<view class="upload-section">
			<view class="upload-area">
				<view class="upload-item" @tap="uploadImage">
					<image src="/static/icons/camera.png" mode="aspectFit" class="upload-icon"></image>
					<text>上传照片</text>
				</view>
				<view class="upload-item" @tap="uploadVideo">
					<image src="/static/icons/video.png" mode="aspectFit" class="upload-icon"></image>
					<text>上传视频</text>
				</view>
			</view>
			<!-- 已上传的图片预览 -->
			<view class="preview-list" v-if="uploadedFiles.length > 0">
				<view class="preview-item" v-for="(file, index) in uploadedFiles" :key="index">
					<!-- 根据文件类型显示不同组件 -->
					<image v-if="file.type === 'image'" 
						:src="file.url" 
						mode="aspectFill" 
						class="preview-image">
					</image>
					<video v-else-if="file.type === 'video'" 
						:src="file.url"
						class="preview-video"
						:controls="false"
						:show-play-btn="true"
						:enable-progress-gesture="false"
						object-fit="cover">
					</video>
					<view class="delete-btn" @tap="deleteFile(index)">×</view>
				</view>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-btn" @tap="submitReport">
			提交申请
		</view>
	</view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
	data() {
		return {
			orderInfo: {
				image: '',
				title: '',
				store: '',
				technician: '',
				time: '',
				price: '',
				memberPrice: ''
			},
			reportOptions: [
				'服务态度问题',
				'服务内容不符',
				'没有效果',
				'个人卫生状况',
				'服务态度恶劣',
				'价格争议',
				'BUG',
				'吐槽'
			],
			selectedOptions: [],
			reportContent: '',
			uploadedFiles: []
		}
	},

	onLoad(options) {
		if (options.id) {
			this.loadOrderInfo(options.id)
		} else {
			uni.showToast({
				title: '缺少订单信息',
				icon: 'none'
			})
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		}
	},

	methods: {
		loadOrderInfo(id) {
			uni.request({
				url: `${uni.$config.baseUrl}/orders/orders/${id}`,
				method: 'GET',
				success: (res) => {
					if (res.statusCode === 200 && res.data.code === 200) {
						const orderData = res.data.data
						this.orderInfo = {
							id: orderData.id,
							image: orderData.img,
							userId:orderData.userId,
							serviceId:orderData.serviceId,
							storeId:orderData.storeId,
							technicianId:orderData.technicianId,
							title: orderData.serviceName,
							store: orderData.storeName,
							technician: orderData.technicianName,
							time: orderData.appointmentDate+"  "+orderData.appointmentTime,
							price: orderData.servicePrice,
							memberPrice: orderData.servicePrice
						}
					} else {
						uni.showToast({
							title: res.data.msg || '获取订单信息失败',
							icon: 'none'
						})
					}
				},
				fail: (err) => {
					console.error('获取订单信息失败:', err)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				}
			})
		},

		toggleOption(option) {
			const index = this.selectedOptions.indexOf(option)
			if (index === -1) {
				this.selectedOptions.push(option)
			} else {
				this.selectedOptions.splice(index, 1)
			}
		},
		
		async uploadImage() {
			try {
				const res = await uni.chooseImage({
					count: 9,
					sizeType: ['compressed']  // 使用压缩图片以减小文件大小
				})
				
				// 显示上传中提示
				uni.showLoading({
					title: '上传中...',
					mask: true
				})

				// 处理每个选中的图片
				const uploadPromises = res.tempFilePaths.map(async (path) => {
					// 获取文件信息以检查大小
					const fileInfo = await new Promise((resolve, reject) => {
						uni.getFileInfo({
							filePath: path,
							success: resolve,
							fail: reject
						})
					})

					// 检查文件大小（2MB = 2 * 1024 * 1024）
					if (fileInfo.size > 2 * 1024 * 1024) {
						throw new Error('文件大小不能超过2MB')
					}

					// 上传文件
					const uploadRes = await uni.uploadFile({
						url: `${uni.$config.baseUrl}/minio/upload`,
						filePath: path,
						name: 'file',
						formData: {
							'Content-Type': 'image/jpeg'
						}
					})

					const data = JSON.parse(uploadRes.data)
					if (data.code === 200) {
						return {
							type: 'image',
							url: data.url
						}
					} else {
						throw new Error(data.msg || '上传失败')
					}
				})

				// 等待所有图片上传完成
				const results = await Promise.all(uploadPromises)
				this.uploadedFiles.push(...results)

				uni.showToast({
					title: '上传成功',
					icon: 'success'
				})
			} catch (err) {
				console.error('上传图片失败:', err)
				uni.showToast({
					title: err.message || '上传失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		async uploadVideo() {
			try {
				const res = await uni.chooseVideo({
					compressed: true,
					sourceType: ['camera', 'album']
				})
				
				// 显示上传中提示
				uni.showLoading({
					title: '上传中...',
					mask: true
				})

				// 上传视频文件
				const uploadRes = await uni.uploadFile({
					url: `${uni.$config.baseUrl}/minio/upload/video`,
					filePath: res.tempFilePath,
					name: 'file',
					formData: {}
				})

				const data = JSON.parse(uploadRes.data)
				if (data.code === 200) {
					// 上传成功，添加到文件列表
					this.uploadedFiles.push({
						type: 'video',
						url: data.url  // 使用返回的视频URL
					})
					
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					})
				} else {
					throw new Error(data.msg || '上传失败')
				}
			} catch (err) {
				console.error('上传视频失败:', err)
				uni.showToast({
					title: err.message || '上传失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		deleteFile(index) {
			this.uploadedFiles.splice(index, 1)
		},
		
		async submitReport() {
			if (this.selectedOptions.length === 0) {
				uni.showToast({
					title: '请选择反馈类型',
					icon: 'none'
				})
				return
			}

			if (!this.reportContent.trim()) {
				uni.showToast({
					title: '请输入申请原因',
					icon: 'none'
				})
				return
			}

			uni.showLoading({
				title: '提交中...'
			})

			try {

				// 构建售后数据
				const afterSalesData = {
					orderId: this.orderInfo.id,
					projectId: this.orderInfo.serviceId,
					userId: this.orderInfo.userId,
					storeId: this.orderInfo.storeId,
					technicianId: this.orderInfo.technicianId,
					feedbackTypes: this.selectedOptions.join(','),
					feedbackContent: this.reportContent,
					mediaUrls: this.uploadedFiles.map(file => file.url).join(','),
					status: 0,
					createBy: uni.getStorageSync('userInfo').userName || ''
				}

				// 提交售后申请
				const res = await uni.request({
					url: `${uni.$config.baseUrl}/aftersales/aftersales`,
					method: 'POST',
					data: afterSalesData
				})

				if (res.data.code === 200) {
					uni.showToast({
						title: '提交成功',
						icon: 'success'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: `/pages/report-list/report-list`
						})
					}, 1500)
				} else {
					throw new Error(res.data.msg || '提交失败')
				}
			} catch (error) {
				uni.showToast({
					title: error.message || '提交失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},

		async uploadFiles() {
			const uploadPromises = this.uploadedFiles.map(file => {
				return new Promise((resolve, reject) => {
					// 检查文件类型
					if (file.type === 'video') {
						reject(new Error('只能上传图片文件'))
						return
					}
					
					// 获取文件信息
					uni.getFileInfo({
						filePath: file.url,
						success: (fileInfo) => {
							// 检查文件大小（2MB = 2 * 1024 * 1024）
							if (fileInfo.size > 2 * 1024 * 1024) {
								reject(new Error('文件大小不能超过2MB'))
								return
							}
							
							// 上传文件
							uni.uploadFile({
								url: `${uni.$config.baseUrl}/minio/upload`,
								filePath: file.url,
								name: 'file',
								formData: {
									'Content-Type': 'image/jpeg'
								},
								success: (res) => {
									try {
										const data = JSON.parse(res.data)
										if (data.code === 200) {
											resolve(data.url)
										} else {
											reject(new Error(data.msg || '文件上传失败'))
										}
									} catch (e) {
										reject(new Error('解析响应数据失败'))
									}
								},
								fail: () => {
									reject(new Error('文件上传失败'))
								}
							})
						},
						fail: () => {
							reject(new Error('获取文件信息失败'))
						}
					})
				})
			})
			
			try {
				const urls = await Promise.all(uploadPromises)
				return urls.filter(url => url) // 过滤掉可能的空值
			} catch (error) {
				uni.showToast({
					title: error.message,
					icon: 'none'
				})
				throw error
			}
		}
	}
}
</script>

<style lang="scss">
.report-detail {
	min-height: 100vh;
	background: #F8F8F8;
	padding-bottom: 120rpx;
	
	.service-info {
		background: #FFFFFF;
		padding: 30rpx;
		display: flex;
		
		.service-image {
			width: 160rpx;
			height: 160rpx;
			margin-right: 20rpx;
			border-radius: 8rpx;
			overflow: hidden;
			
			image {
				width: 100%;
				height: 100%;
			}
		}
		
		.service-content {
			flex: 1;
			
			.service-title {
				font-size: 32rpx;
				color: #333;
				font-weight: 500;
				margin-bottom: 12rpx;
			}
			
			.service-meta {
				font-size: 26rpx;
				color: #666;
				margin-bottom: 12rpx;
				
				.time {
					margin-left: 20rpx;
				}
			}
			
			.price-info {
				.original-price {
					font-size: 32rpx;
					color: #333;
					margin-right: 20rpx;
				}
				
				.member-price {
					font-size: 26rpx;
					color: #FF6B6B;
				}
			}
		}
	}
	
	.report-options {
		margin-top: 20rpx;
		background: #FFFFFF;
		padding: 30rpx;
		
		.option-title {
			font-size: 30rpx;
			color: #333;
			margin-bottom: 20rpx;
		}
		
		.options-grid {
			display: flex;
			flex-wrap: wrap;
			
			.option-item {
				width: calc(33.33% - 20rpx);
				height: 80rpx;
				margin: 10rpx;
				background: #F8F8F8;
				border-radius: 8rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 26rpx;
				color: #666;
				
				&.active {
					background: #2B87FF;
					color: #FFFFFF;
				}
			}
		}
	}
	
	.report-detail-input {
		margin-top: 20rpx;
		background: #FFFFFF;
		padding: 30rpx;
		
		.detail-textarea {
			width: 100%;
			height: 200rpx;
			font-size: 28rpx;
			color: #333;
			line-height: 1.5;
		}
	}
	
	.upload-section {
		margin-top: 20rpx;
		background: #FFFFFF;
		padding: 30rpx;
		
		.upload-area {
			display: flex;
			margin-bottom: 20rpx;
			
			.upload-item {
				width: 160rpx;
				height: 160rpx;
				background: #F8F8F8;
				border-radius: 8rpx;
				margin-right: 20rpx;
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				
				.upload-icon {
					width: 60rpx;
					height: 60rpx;
					margin-bottom: 10rpx;
				}
				
				text {
					font-size: 24rpx;
					color: #666;
				}
			}
		}
		
		.preview-list {
			display: flex;
			flex-wrap: wrap;
			
			.preview-item {
				width: 160rpx;
				height: 160rpx;
				margin: 10rpx;
				position: relative;
				overflow: hidden;
				
				.preview-image,
				.preview-video {
					width: 100%;
					height: 100%;
					border-radius: 8rpx;
				}
				
				.preview-video {
					object-fit: cover;
				}
				
				.delete-btn {
					position: absolute;
					top: -10rpx;
					right: -10rpx;
					width: 40rpx;
					height: 40rpx;
					background: rgba(0, 0, 0, 0.5);
					border-radius: 20rpx;
					color: #FFFFFF;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 24rpx;
				}
			}
		}
	}
	
	.submit-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background: #2B87FF;
		color: #FFFFFF;
		font-size: 32rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		
		&:active {
			opacity: 0.9;
		}
	}
}
</style> 